<template>
  <div class="adoption-container">
    <div class="banner" style="background-image: url('/src/assets/background/bg1.jpg')">
      <h1 class="page-title">为它们寻找一个温暖的家</h1>
      <p class="page-subtitle">每一个生命都值得被珍惜和关爱</p>
    </div>

    <div class="content">
      <!-- 筛选条件 -->
      <div class="filter-section">
        <el-card class="filter-card">
          <h3 class="filter-title">寻找心仪的小伙伴</h3>
          <div class="filter-buttons">
            <el-button :type="filterType === '' ? 'primary' : ''" @click="handleTypeSelect('')">
              全部
            </el-button>
            <el-button v-for="type in types" :key="type.id" :type="filterType === type.id ? 'primary' : ''"
              @click="handleTypeSelect(type.id)">
              {{ type.type }}
            </el-button>
          </div>
        </el-card>
      </div>

      <!-- 宠物列表 -->
      <div class="pets-section">
        <div class="pet-grid">
          <el-card v-for="pet in pets" :key="pet.id" class="pet-card" shadow="hover">
            <div class="pet-image-container">
              <img :src="`/api/Petfile/${pet.image}`" class="pet-image" :alt="pet.pet_name" />
              <div class="pet-status" :class="pet.status === 'available' ? 'available' : 'adopted'">
                {{ pet.status === 'available' ? '待领养' : '已领养' }}
              </div>
            </div>
            <div class="pet-info">
              <h3 class="pet-name">{{ pet.pet_name }}</h3>
              <p class="pet-description">{{ pet.pet_character }}</p>
              <div class="pet-details">
                <el-tag size="small" type="success">{{ pet.age }}岁</el-tag>
                <el-tag size="small" type="warning">{{ pet.gender === 'female' ? '母' : '公' }}</el-tag>
                <el-tag size="small" type="info">{{ pet.petTypeName }}</el-tag>
              </div>
              <div class="pet-actions">
                <el-button type="primary" class="adopt-btn" @click="handleAdopt(pet)">
                  申请领养
                </el-button>
                <el-button type="text" class="details-btn" @click="viewDetails(pet)">
                  查看详情
                </el-button>
              </div>
            </div>
          </el-card>
        </div>

        <div class="pagination-container">
          <el-pagination 
            background 
            layout="total, sizes, prev, pager, next, jumper"
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[6,12,18]"
            :total="totalPets"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
          />
        </div>
      </div>
    </div>

    <!-- 添加领养申请对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="申请领养"
      width="30%"
      :before-close="handleClose"
    >
      <el-form
        ref="formRef"
        :model="adoptionForm"
        :rules="rules"
      >
        <el-form-item label="领养理由" prop="reason">
          <el-input v-model="adoptionForm.reason" type="textarea" :rows="4" />
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="adoptionForm.address" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="submitAdoption">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import request from '@/utils/request'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

const router = useRouter()

// 筛选条件
const filterType = ref('')
const types = ref([])

// 分页相关
const currentPage = ref(1)
const pageSize = ref(6)
const totalPets = ref(0)

// 获取所有动物类型
const getTypes = async () => {
  try {
    const res = await request.get('/types/all')
    types.value = res.data
  } catch (error) {
    console.error('获取动物类型失败:', error)
  }
}

// 宠物数据
const pets = ref([])

// 获取宠物列表数据
const getPets = async () => {
  try {
    const res = await request.get('/pet/petSearch', {
      params: {
        pageSize: pageSize.value,
        pageNum: currentPage.value,
        type: filterType.value,
        status:'available'
      }
    })
    pets.value = res.data.list
    totalPets.value = res.data.total
  } catch (error) {
    console.error('获取宠物列表失败:', error)
  }
}

onMounted(() => {
  getTypes()
  getPets()
})

// 方法
const handleTypeSelect = (typeId) => {
  filterType.value = typeId
  currentPage.value = 1
  getPets()
}

const handleSizeChange = (size) => {
  pageSize.value = size
  getPets()
}

const handlePageChange = (page) => {
  currentPage.value = page
  getPets()
}

// 添加领养申请相关的状态和方法
const dialogVisible = ref(false)
const adoptionForm = ref({
  user_id: 1, // 这里应该从用户登录状态获取
  pet_id: '',
  reason: '',
  status: 'pending',
  address: '',
  review_comment: null,
  created_at: new Date().toISOString(),
  updated_at: new Date().toISOString()
})

// 表单验证规则
const rules = {
  reason: [
    { required: true, message: '请填写领养理由', trigger: 'blur' },
    { min: 10, message: '领养理由至少10个字符', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请填写详细地址', trigger: 'blur' }
  ]
}

const formRef = ref(null)

// 处理领养申请
const handleAdopt = (pet) => {
  adoptionForm.value.pet_id = pet.id
  dialogVisible.value = true
}

// 提交领养申请
const submitAdoption = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await request.post('/applications/applicationAdd', adoptionForm.value)
        ElMessage.success('申请提交成功，我们会尽快与您联系！')
        dialogVisible.value = false
      } catch (error) {
        console.error('提交申请失败:', error)
        ElMessage.error('提交申请失败，请稍后重试')
      }
    }
  })
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

const viewDetails = (pet) => {
  router.push(`/front/pet/${pet.id}`)
}
</script>

<style scoped>
.adoption-container {
  background-color: #f5f7fa;
  min-height: 100vh;
}

.banner {
  background-size: cover;
  background-position: center;
  padding: 200px 20px;
  text-align: center;
  color: white;
  position: relative;
  transition: all 0.5s ease;
}

.banner::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.4);
  z-index: 1;
  transition: background 0.3s ease;
}

.banner:hover::before {
  background: rgba(0, 0, 0, 0.3);
}

.page-title {
  font-size: 42px;
  margin-bottom: 20px;
  font-weight: 700;
  position: relative;
  z-index: 2;
  text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
  letter-spacing: 2px;
}

.page-subtitle {
  font-size: 20px;
  opacity: 0.95;
  position: relative;
  z-index: 2;
  text-shadow: 1px 1px 3px rgba(0,0,0,0.2);
  letter-spacing: 1px;
}

.content {
  max-width: 1280px;
  margin: 0 auto;
  padding: 20px;
}

.filter-section {
  margin: -90px auto 40px;
  position: relative;
  z-index: 1;
}

.filter-card {
  border-radius: 16px;
  box-shadow: 0 6px 16px rgba(0,0,0,0.12);
  backdrop-filter: blur(10px);
  background: rgba(255,255,255,0.95);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.filter-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 20px rgba(0,0,0,0.15);
}

.filter-title {
  color: #303133;
  margin-bottom: 25px;
  font-size: 22px;
  font-weight: 600;
  text-align: center;
}

.filter-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  justify-content: center;
}

.pet-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 30px;
  margin-bottom: 50px;
}

.pet-card {
  border-radius: 16px;
  overflow: hidden;
  transition: all 0.4s ease;
  background: white;
}

.pet-card:hover {
  transform: translateY(-8px);
  box-shadow: 0 12px 24px rgba(0,0,0,0.15);
}

.pet-image-container {
  position: relative;
  overflow: hidden;
}

.pet-image {
  width: 100%;
  height: 240px;
  object-fit: cover;
  transition: transform 0.5s ease;
}

.pet-card:hover .pet-image {
  transform: scale(1.08);
}

.pet-status {
  position: absolute;
  top: 15px;
  right: 15px;
  padding: 6px 14px;
  border-radius: 20px;
  color: white;
  font-size: 13px;
  font-weight: 500;
  backdrop-filter: blur(4px);
  box-shadow: 0 2px 6px rgba(0,0,0,0.1);
}

.pet-status.available {
  background-color: rgba(103, 194, 58, 0.9);
}

.pet-status.adopted {
  background-color: rgba(144, 147, 153, 0.9);
}

.pet-info {
  padding: 25px;
}

.pet-name {
  font-size: 20px;
  color: #303133;
  margin-bottom: 12px;
  font-weight: 600;
}

.pet-description {
  color: #606266;
  margin: 15px 0;
  font-size: 14px;
  line-height: 1.7;
}

.pet-details {
  margin: 18px 0;
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.pet-actions {
  display: flex;
  align-items: center;
  gap: 18px;
  margin-top: 20px;
}

.adopt-btn {
  flex: 1;
  padding: 10px 20px;
  font-weight: 500;
  letter-spacing: 1px;
  transition: all 0.3s ease;
}

.adopt-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64,158,255,0.3);
}

.details-btn {
  color: #409EFF;
  font-weight: 500;
  transition: all 0.3s ease;
}

.details-btn:hover {
  color: #66b1ff;
  transform: translateX(3px);
}

.pagination-container {
  text-align: center;
  margin-top: 50px;
  padding-bottom: 40px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .page-title {
    font-size: 32px;
  }
  
  .page-subtitle {
    font-size: 16px;
  }
  
  .pet-grid {
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    gap: 20px;
  }
  
  .filter-section {
    margin: -60px auto 30px;
  }
}
</style>